// dep: JSON Util persist PersistForm

// name of store
// top is top level node to scan for "durable forms
// top defaults to document if not specified
var PersistForms = function( name, top ) {

	this.setStore = function( store ) {
		this.store_ = store;
	};

	this.getStore = function() {
		return this.store_;
	};
	
	this.setForms = function( forms ) {
		this.forms_ = forms;
	};

	this.getForms = function() {
		return this.forms_;
	};

	this.addForm = function( id ) {
		var form = new PersistForm( this.getStore() , id );
		this.getForms().push( form );
		this.getNameToForm()[ id ] = form;
	};

	this.setNameToForm = function( nameToForm ) {
		this.nameToForm_ = nameToForm;
	};

	this.getNameToForm = function() {
		return this.nameToForm_;
	};

	this.getFormByName = function( name ) { 
		return this.getNameToForm()[ name ];
	};

	this.saveForm = function( name ) {
		this.saveByName( name );
	};

	this.saveByName = function( name ) {
		this.getFormByName( name ).save();
	};

	this.setName = function( name ) {
		this.name_ = name;
	};

	this.getName = function() {
		return this.name_;
	};

	this.save = function() {
		for ( var i = 0 ; i < this.getForms().length ; i++ ) {
			this.getForms()[ i ].save();
		}
	};

	this.onLoad = function( top ) {
		if ( !top ) { 
			top = document;
		}

		var thiz = this;
		this.setStore( new Persist.Store( this.getName() ) );

		Util.walkNode(
			top
			, function( node ) {
				return (
					Util.isTag( node, 'FORM' ) 
					&& node.getAttribute( 'id' )
					&& Util.hasClass( node, 'durable' )
				); 
			}
			, function( node ) {
				var id = node.getAttribute( 'id' );
				thiz.addForm( node.getAttribute( 'id' ) );
			}
		);
	};

	this.init = function( name, top ) {
		this.setForms( [] );
		this.setNameToForm( [] );

		this.setName( name );
		var thiz = this;
		Util.addOnLoadCallback( function() { thiz.onLoad( top ); } );
	};

	this.init( name, top );

};
